package com.koro.service;

import com.alibaba.fastjson.JSONObject;
import com.koro.tools.ExcelUtils;
import com.koro.vo.CityCodeVO;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatusCode;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author HQ
 */
@Service
public class WeatherService {

    private final RestClient restClient;

    @Value("${gd.key}")
    private String GD_KEY;


    public WeatherService() {
        this.restClient = RestClient.builder()
                .baseUrl("https://restapi.amap.com/")
                .defaultHeader("Accept", "application/geo+json")
                .defaultHeader("User-Agent", "WeatherApiClient/1.0")
                .build();
    }

    @Tool(description = "根据城市名称获取天气预报信息")
    public String getWeather(@ToolParam(description = "城市") String cityName) throws IOException {
        Map<String, Integer> cityMap = new HashMap<>();
        String filePath = "xlsx/AMap_adcode_citycode.xlsx";
        List<CityCodeVO> excel = ExcelUtils.readExcel(filePath, CityCodeVO.class);
        excel.forEach(e -> cityMap.put(e.getCityName(), e.getAdcode()));
        List<String> collect = cityMap.keySet().stream().filter(key -> key.contains(cityName)).collect(Collectors.toList());
        return restClient.get().uri(uriBuilder -> uriBuilder
                .path("v3/weather/weatherInfo")
                .queryParam("key", GD_KEY)
                .queryParam("city", cityMap.get(collect.get(0)))
                .build()).retrieve() // 获取响应
                .onStatus(HttpStatusCode::is4xxClientError, (req, res) -> { // 处理4xx错误
                    System.out.println("请求的uri" + req.getURI());
                })
                .body(String.class);
    }


    @Tool(description = "路线规划")
    public String getRoutePlan(@ToolParam(description = "起点")String originAddress, @ToolParam(description = "目的地")String destAddress,
                               @ToolParam(description = "方式")String mode) {
        // 起点经纬度
        String origin = getLatitudeLongitude(originAddress);
        // 目的地经纬度
        String dest= getLatitudeLongitude(destAddress);

        String uri = null;

        if (mode.equals("公交") || mode.equals("bus")) {
            uri = "v5/direction/transit/integrated";
        } else if (mode.equals("驾车") || mode.equals("driving") || mode.equals("driv")) {
            uri = "v5/direction/driving";
        } else if (mode.equals("步行") || mode.equals("walking") || mode.equals("walk")) {
            uri = "v5/direction/walking";
        } else if (mode.equals("骑行") || mode.equals("bicycling") || mode.equals("bike")) {
            uri = "v5/direction/bicycling";
        } else if (mode.equals("电车") || mode.equals("electrobike")) {
            uri = "v5/direction/electrobike";
        }

        // 路线规划
        String finalUri = uri;
        return restClient.get().uri(uriBuilder -> uriBuilder
                .path(finalUri)
                .queryParam("key", GD_KEY)
                .queryParam("origin", origin)
                .queryParam("destination", dest)
                .build()).retrieve() // 获取响应
                .onStatus(HttpStatusCode::is4xxClientError, (req, res) -> { // 处理4xx错误
                    System.out.println("请求的uri" + req.getURI());
                })
                .body(String.class);
    }

    /**
     * 获取经纬度
     * @param address
     * @return
     */
    private String getLatitudeLongitude(String address) {
        JSONObject body = restClient.get().uri(uriBuilder -> uriBuilder
                .path("v3/geocode/geo")
                .queryParam("key", GD_KEY)
                .queryParam("address", address)
                .build()).retrieve() // 获取响应
                .onStatus(HttpStatusCode::is4xxClientError, (req, res) -> { // 处理4xx错误
                    System.out.println("请求的uri" + req.getURI());
                })
                .body(JSONObject.class);
        return body.getJSONArray("geocodes").getJSONObject(0).getString("location");
    }
}
